<template>
  <!-- 养殖进场 -->
  <view class="form-filling-page-box">
    <!-- 上面那一块的样式结束-->
    <!-- 表单开始 -->
    <Navbar navbarTitle="养殖进场"></Navbar>
    <view class="form-validation-box">
      <uni-forms ref="formValidation"
                 :modelValue="alignmentFormData"
                 validateTrigger="bind"
                 :rules="custRules"
                 label-position="top"
                 labelWidth="100px">
        <!-- <uni-forms-item label="所属基地"
                        required
                        name="baseId">
          <uni-data-select placeholder="请选择所属基地"
                           v-model="alignmentFormData.baseId"
                           :localdata="foundedTime"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="所属栏舍"
                        required
                        name="hutsId">
          <uni-data-select placeholder="请选择所属栏舍"
                           v-model="alignmentFormData.hutsId"
                           :localdata="foundedTime"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="养殖栏"
                        required
                        name="feedHutsId">
          <uni-data-select placeholder="请选择养殖栏"
                           v-model="alignmentFormData.feedHutsId"
                           :localdata="foundedTime"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item> -->
        <uni-forms-item label="所属养殖栏"
                        required
                        name="livestockPenArr">
          <uni-data-picker placeholder="请选择所属养殖栏"
                           popup-title="请选择"
                           :localdata="dataTree"
                           v-model="alignmentFormData.livestockPenArr"
                           :map="{text:'name',value:'id'}"
                           @change="onchange">

          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="耳标号"
                        required
                        name="earTag">
          <uni-easyinput v-model="alignmentFormData.earTag"
                         placeholder="请输入耳标号" />
        </uni-forms-item>
        <uni-forms-item label="性别"
                        required
                        name="sex">
          <uni-data-select placeholder="请选择性别"
                           v-model="alignmentFormData.sex"
                           :localdata="$store.getters.getDictionaryItem('sys_user_sex')"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="羊只类别"
                        required
                        name="kind">
          <uni-data-select placeholder="请选择羊只类别"
                           v-model="alignmentFormData.kind"
                           :localdata="$store.getters.getDictionaryItem('goat_kind')"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="来源方式"
                        required
                        name="source">
          <uni-data-select placeholder="请选择来源方式"
                           v-model="alignmentFormData.source"
                           :localdata="$store.getters.getDictionaryItem('goat_from')"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="饲养方式"
                        required
                        name="feedType">
          <uni-data-select placeholder="请选择饲养方式"
                           v-model="alignmentFormData.feedType"
                           :localdata="$store.getters.getDictionaryItem('feed_type')"
                           :clear="false">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="出生日期"
                        required
                        name="birthTime">
          <uni-datetime-picker type="date"
                               :clear-icon="false"
                               placeholder="请选择出生日期"
                               v-model="alignmentFormData.birthTime" />
        </uni-forms-item>
        <uni-forms-item label="入场日龄"
                        required
                        name="insideDay">
          <uni-easyinput type="number"
                         v-model="alignmentFormData.insideDay"
                         placeholder="请输入入场日龄" />
          <text class="unit">天</text>
        </uni-forms-item>
        <uni-forms-item label="入场重量"
                        required
                        name="insideWeight">
          <uni-easyinput type="number"
                         v-model="alignmentFormData.insideWeight"
                         placeholder="请输入入场重量" />
          <text class="unit">KG</text>
        </uni-forms-item>
        <uni-forms-item label="入场操作员"
                        required
                        name="insideName">
          <uni-easyinput v-model="alignmentFormData.insideName"
                         placeholder="请输入入场操作员" />
        </uni-forms-item>
        <uni-forms-item required
                        label="入场日期"
                        name="insideTime">
          <uni-datetime-picker type="date"
                               :clear-icon="false"
                               placeholder="请选择入场日期"
                               v-model="alignmentFormData.insideTime" />
        </uni-forms-item>
        <uni-forms-item required
                        label="羊只图片"
                        name="pictPath">
          <FileUpload @uploadSuccess="uploadSuccess" />
        </uni-forms-item>
      </uni-forms>
    </view>
    <!-- 表单结束 -->
    <view class="button-assembly-box">
      <button @click="scanCodes"
              class="button reset">扫码</button>
      <button @click="reset"
              class="button reset">重置</button>
      <button @click="submit"
              class="button notarize">确认</button>
    </view>
  </view>
</template>

<script>
import Navbar from '@/components/common/Navbar.vue'
import FileUpload from '@/components/FileUpload.vue'
export default {
  components: {
    Navbar,
    FileUpload
  },
  data () {
    return {
      dataTree: [],
      alignmentFormData: {
        livestockPenArr: '',
        baseId: '',
        feedHutsId: '',
        hutsId: '',
        earTag: '',
        sex: '',
        kind: '',
        source: '',
        feedType: '',
        birthTime: '',
        insideDay: '',
        insideWeight: '',
        insideName: '',
        insideTime: '',
        pictPath: ''
      },
      custRules: {
        livestockPenArr: {
          rules: [{
            required: true,
            errorMessage: '请选择所属养殖栏',
          }]
        },
        earTag: {
          rules: [{
            required: true,
            errorMessage: '请输入耳标号',
          }]
        },
        sex: {
          rules: [{
            required: true,
            errorMessage: '请选择性别',
          }]
        },
        kind: {
          rules: [{
            required: true,
            errorMessage: '请选择羊只类别',
          }]
        },
        source: {
          rules: [{
            required: true,
            errorMessage: '请选择来源方式',
          }]
        },
        feedType: {
          rules: [{
            required: true,
            errorMessage: '请选择饲养方式',
          }]
        },
        birthTime: {
          rules: [{
            required: true,
            errorMessage: '请选择出生日期',
          }]
        },
        insideDay: {
          rules: [{
            required: true,
            errorMessage: '请输入入场日龄',
          }, {
            validateFunction: function (rule, value, data, callback) {
              let arr = value?.split('.');
              if (arr.length > 1) {
                callback('应为正整数')
              }
              return true
            }
          }]
        },
        insideName: {
          rules: [{
            required: true,
            errorMessage: '请输入入场操作员',
          }]
        },
        pictPath: {
          rules: [{
            required: true,
            errorMessage: '请选择羊只图片',
          }]
        },
        insideTime: {
          rules: [{
            required: true,
            errorMessage: '请选择入场日期',
          }]
        },
        insideWeight: {
          rules: [
            {
              required: true,
              errorMessage: '请输入',
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let arr = value?.split('.');
                if (value > 999.99 || value < 0) {
                  callback('应在数值 0 - 999.99 之间')
                }
                if (arr[0].length > 3) {
                  callback('整数部分最多3位数')
                }
                if (arr[1]?.length > 2) {
                  callback('小数部分最多2位数')
                }
                return true
              }
            }
          ]
        }
      }
    }
  },
  mounted () {
    this.getBreedingPen()
  },
  methods: {
    uploadSuccess (value) {
      this.alignmentFormData.pictPath = value
    },
    // 获取养殖栏等信息
    async getBreedingPen () {
      const res = await this.$api.breedingModuleServer.getGoatBaseList();
      if (res.code === 200) {
        this.dataTree = res.data
      }
    },
    // 当选择了养殖栏的时候
    onchange (e) {
      const arr = e.detail.value
      if (arr.length === 3) {
        this.alignmentFormData.baseId = arr[0]
        this.alignmentFormData.feedHutsId = arr[2]
        this.alignmentFormData.hutsId = arr[1]
        return
      }
      this.alignmentFormData.baseId = ''
      this.alignmentFormData.feedHutsId = ''
      this.alignmentFormData.hutsId = ''
      uni.showToast({
        icon: "error",
        title: '请选择三级的值'
      })
    },
    // 点击重置按钮
    reset () {
      this.alignmentFormData = {
        livestockPenArr: '',
        baseId: '',
        feedHutsId: '',
        hutsId: '',
        earTag: '',
        sex: '',
        kind: '',
        source: '',
        feedType: '',
        birthTime: '',
        insideDay: '',
        insideWeight: '',
        insideName: '',
        insideTime: '',
        pictPath: ''
      }
      setTimeout(() => {
        this.$refs.formValidation.clearValidate()
      }, 17)
    },
    // 进行扫码
    scanCodes () {
      // 调起后置摄像头扫码
      uni.scanCode({
        scanType: ['barCode', 'qrCode', 'pdf417', 'datamatrix'],
        success: (res) => {
          this.alignmentFormData.earTag = res.result;
        },
        fail: (err) => {
          // 扫描失败回调
          uni.showToast({
            icon: "error",
            title: '扫码失败',
            duration: 2000,
          });
        }
      });
    },
    // 点击确定按钮
    submit () {
      this.$refs['formValidation'].validate().then(async () => {
        const res = await this.$api.breedingModuleServer.goatInfoAdd(this.alignmentFormData);
        if (res.code !== 200) return
        uni.showToast({
          title: '新增成功',
          icon: 'success'
        })
      }).catch((err) => {
        uni.showToast({
          title: err[0].errorMessage,
          icon: 'error'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-filling-page-box {
  // height: 100vh;
  width: 100vw;
  background: #fff;
  .button-assembly-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100vw - 64rpx);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx 30rpx;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 -4px 8px 0 rgba(0, 0, 0, 0.04), 0 0 1px 0 rgba(0, 0, 0, 0.04);

    .button {
      margin: 0;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 40rpx;
      background-color: #fff;
    }

    .reset {
      width: 156rpx;
      margin-right: 24rpx;
      border: 1rpx solid #e7e7e7;
    }

    .notarize {
      flex: 1;
      color: #fff;
      background: $uni-color-success;
    }

    .button::after {
      border: 0;
    }
  }

  .form-validation-box {
    padding: 56rpx 32rpx 140rpx;
    background-color: #fff;
    border-radius: 32rpx;
    z-index: 12;
    .title {
      display: block;
      color: #333;
      font-size: 28rpx;
      font-weight: 500;
      padding: 24rpx 0;
    }

    /deep/.uni-forms-item {
      margin-bottom: 40rpx;

      .uni-forms-item__content {
        position: relative;
        .uni-select,
        .input-value {
          background-color: #fff;
        }

        .unit {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          right: 32rpx;
          color: #333;
          font-size: 24rpx;
          font-weight: 400;
        }
      }

      .input-value-border,
      .uni-date-editor--x,
      .uni-date-x--border,
      .uni-date-x,
      .uni-date-single,
      .uni-select {
        border-radius: 45rpx !important;
        font-size: 28rpx !important;
        border-color: #e7e7e7;
        height: 78rpx;
      }

      .uni-easyinput__content {
        border-radius: 45rpx;
        border-color: #e7e7e7;

        .uni-icons {
          color: #e7e7e7 !important;
          display: none;
        }
      }

      .is-focused {
        border-color: #e7e7e7 !important;
      }

      .uni-forms-item__label {
        flex-direction: row-reverse;
        justify-content: flex-end !important;
        color: #333;
        font-size: 24rpx;
        height: 40rpx;
        font-weight: 400;
        padding-bottom: 20rpx;

        .is-required {
          margin: 4rpx 0 0 8rpx;
          color: red;
        }
      }
    }
  }
}
</style>